package com.ycy.lucene.search;

import com.ycy.lucene.index.IndexCreateDemo;
import org.apache.lucene.document.Document;
import org.apache.lucene.index.DirectoryReader;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.search.*;
import org.apache.lucene.store.FSDirectory;

import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.Paths;

/**
 * 分页查询
 * <p>
 * 3.5版本之后提供了一个 searchAfter功能
 */
public class PageSizeQuery {


  /**
   * 会把所有查询结果加载到内存中
   *
   * @param query
   */
  public static void searchPage(Query query, Sort sort, int index, int pageSize) {
    try {
      Path path = Paths.get(IndexCreateDemo.indexpath);
      IndexReader indexReader = DirectoryReader.open(FSDirectory.open(path));
      IndexSearcher isearch = new IndexSearcher(indexReader);

      //检索500,一般用户查询10页,会把内存中500个元素加载进来
      TopDocs search = isearch.search(query, 500, sort);
//      TopDocs search = isearch.search(query, 500);
      ScoreDoc[] scoreDocs = search.scoreDocs;

      int start = (index - 1) * pageSize;
      int end = index * pageSize;

      if (end > scoreDocs.length) {
        end = scoreDocs.length;
      }

      for (int i = start; i < end; i++) {
        ScoreDoc scoreDoc = scoreDocs[i];
        Document doc = isearch.doc(scoreDoc.doc);
        String res = String.format("docid--> %s scoreDoc--> %s id--> %s name--> %s opendate--> %s ",
                scoreDoc.doc, scoreDoc.score, doc.get("id"), doc.get("name"), doc.get("opendate"));
        System.out.println(res);
      }
      System.out.println("共检索出 " + search.totalHits + " 条记录");

    } catch (IOException e) {
      e.printStackTrace();
    }
  }


  /**
   * 优化上一个方法,
   */
  public static void searchPagemize() {

  }


}
